<template>
  <div id="addQuestionView">
    <a-form :model="form" label-align="left" auto-label-width>
      <a-form-item field="title" label="标题：">
        <a-input
          v-model="form.title"
          placeholder="请输入标题"
          style="width: 600px"
        />
      </a-form-item>
      <a-form-item field="tags" label="标签：">
        <a-input-tag
          v-model="form.tags"
          placeholder="请选择标签"
          allow-clear
          style="width: 600px"
        />
      </a-form-item>
      <a-form-item field="content" label="题目内容：">
        <MdEditor
          @click="
            contentZIndex = 2;
            answerZIndex = 1;
          "
          :style="`z-index: ${contentZIndex}`"
          mode="split"
          :value="form.content"
          :handle-change="onContentChange"
        />
      </a-form-item>
      <a-form-item field="answer" label="答案：">
        <MdEditor
          @click="
            contentZIndex = 1;
            answerZIndex = 2;
          "
          :style="`z-index: ${answerZIndex}`"
          mode="split"
          :value="form.answer"
          :handle-change="onAnswerChange"
        />
      </a-form-item>

      <a-form-item
        label="判题配置："
        :content-flex="false"
        :merge-props="false"
      >
        <a-space direction="vertical">
          <a-form-item
            field="judgeConfig.memoryLimit"
            label="时间限制(ms)："
            style="min-width: 480px"
          >
            <a-input-number
              v-model="form.judgeConfig.timeLimit"
              placeholder="请输入时间限制"
              mode="button"
              min="0"
              size="large"
            />
          </a-form-item>

          <a-form-item
            field="judgeConfig.memoryLimit"
            label="内存限制(MB)："
            style="min-width: 480px"
          >
            <a-input-number
              v-model="form.judgeConfig.memoryLimit"
              placeholder="请输入内存限制"
              mode="button"
              min="0"
              size="large"
            />
          </a-form-item>

          <a-form-item
            field="judgeConfig.stackLimit"
            label="堆栈限制(MB)："
            style="min-width: 480px"
          >
            <a-input-number
              v-model="form.judgeConfig.stackLimit"
              placeholder="请输入堆栈限制"
              mode="button"
              min="0"
              size="large"
            />
          </a-form-item>
        </a-space>
      </a-form-item>

      <a-form-item
        label="判题测试用例："
        :content-flex="false"
        :merge-props="false"
      >
        <a-form-item
          v-for="(judgeCaseItem, index) of form.judgeCase"
          :key="index"
          no-style
        >
          <a-space direction="vertical" style="min-width: 480px">
            <a-form-item
              :field="`form.judgeCase[${index}].input`"
              :label="`输入用例-${index + 1}`"
              :key="index"
            >
              <a-input
                v-model="judgeCaseItem.input"
                placeholder="测试输入用例"
              />
            </a-form-item>

            <a-form-item
              :field="`form.judgeCase[${index}].output`"
              :label="`输出用例-${index + 1}`"
              :key="index"
            >
              <a-input
                v-model="judgeCaseItem.output"
                placeholder="测试输出用例"
              />
            </a-form-item>
            <a-button @click="handleDelete(index)" status="danger"
              >删除
            </a-button>
          </a-space>
        </a-form-item>
        <div style="margin-top: 32px">
          <a-button @click="handleAdd" type="outline" status="success"
            >新增测试用例
          </a-button>
        </div>
      </a-form-item>

      <div style="margin-top: 16px" />
      <a-form-item>
        <a-button type="primary" style="min-width: 200px" @click="doSubmit"
          >提交
        </a-button>
      </a-form-item>
    </a-form>
  </div>
</template>

<script setup lang="ts">
import { onMounted, reactive, ref, watchEffect } from "vue";
import MdEditor from "@/components/MdEditor.vue";
import { QuestionControllerService } from "../../../generated";
import message from "@arco-design/web-vue/es/message";
import { useRoute, useRouter } from "vue-router";

const contentZIndex = ref(1);
const answerZIndex = ref(1);

const route = useRoute();

const form = ref({
  answer: "",
  content: "",
  judgeCase: [
    {
      input: "",
      output: "",
    },
  ],
  judgeConfig: {
    memoryLimit: 20,
    stackLimit: 20,
    timeLimit: 3000,
  },
  tags: [],
  title: "",
});

//如果路由路径包含update，则为更新页面
const updatePage = route.path.includes("update");

/**
 * 根据题目id获取老的数据
 */
const loadData = async () => {
  const id = route.query.id;
  if (!id) {
    return;
  }
  const res = await QuestionControllerService.getQuestionByIdUsingGet(
    id as any
  );
  if (res.code === 0) {
    form.value = res.data as any;
    //json 转 js对象
    if (!form.value.judgeCase) {
      //如果judgeCase为空，给个默认值
      form.value.judgeCase = [
        {
          input: "",
          output: "",
        },
      ];
    } else {
      form.value.judgeCase = JSON.parse(form.value.judgeCase as any);
    }
    if (!form.value.judgeConfig) {
      //如果judgeConfig为空，给个默认值
      form.value.judgeConfig = {
        memoryLimit: 1000,
        stackLimit: 1000,
        timeLimit: 1000,
      };
    } else {
      form.value.judgeConfig = JSON.parse(form.value.judgeConfig as any);
    }
    if (!form.value.tags) {
      form.value.tags = [];
    } else {
      form.value.tags = JSON.parse(form.value.tags as any);
    }
  } else {
    message.error("加载失败" + res.message);
  }
};

onMounted(() => {
  loadData();
});

/**
 * 发送创建或修改题目请求到后端
 */
const doSubmit = async () => {
  //区分该请求是更新还是创建
  if (updatePage) {
    const res = await QuestionControllerService.updateQuestionUsingPut(
      form.value
    );
    if (res.code === 0) {
      message.success("更新成功");
      //跳转页面
      toQuestionManagerViewPage();
    } else {
      message.error("更新失败" + res.message);
    }
  } else {
    const res = await QuestionControllerService.addQuestionUsingPost(
      form.value
    );
    if (res.code === 0) {
      message.success("创建成功");
      //跳转页面
      toQuestionManagerViewPage();
    } else {
      message.error("创建失败" + res.message);
    }
  }
};
const router = useRouter();
/**
 * 跳转到题目管理页面
 */
const toQuestionManagerViewPage = () => {
  router.push({
    path: `/manage/question`,
  });
};

/**
 * 新增判题用例
 */
const handleAdd = () => {
  form.value.judgeCase.push({
    input: "",
    output: "",
  });
};
/**
 * 删除判题用例
 * @param index
 */
const handleDelete = (index: number) => {
  form.value.judgeCase.splice(index, 1);
};

const onAnswerChange = (value: string) => {
  form.value.answer = value;
};
const onContentChange = (value: string) => {
  form.value.content = value;
};
</script>

<style scoped>
#addQuestionView {
}
</style>
